package com.itheima.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjecthandler implements MetaObjectHandler {
    /**
     * mybatisplus的新增方法的时候触发
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("insert fill...");

        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser",1L );
        metaObject.setValue("createUser", 1L);
    }

    /**
     * mybatisplus的修改方法的时候触发
     * @param metaObject
     */

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ...");

        log.error("线程id={}",Thread.currentThread().getId());

//        //方法二
//        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//        ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes) requestAttributes;
//        HttpServletRequest request = servletRequestAttributes.getRequest();
//        HttpSession session = request.getSession();
//        Long empId = (Long) session.getAttribute("empId");

        metaObject.setValue("updateTime",LocalDateTime.now());
        //方法一
        metaObject.setValue("updateUser", BaseContext.getId());
//        //方法二(不建议)
//        metaObject.setValue("updateUser", empId);
    }
}
